/* Copyright (c) 2009-2010, Sean A.O. Harney <sharney3@gmail.com> */

#include "omf.h"


// expects already evaled leaf expr of type INT for 1st arg
//expects already evaled leaf expr for 2nd arg
// expr0 is path, expr1 is fopen mode (e.g. "r+") whatever underlying libc supports is supported by OMF so may vary on diff systems.

EXPR_P builtin_func_write(EXPR_P expr_fd, EXPR_P expr_data)
{
    if (expr_fd->u.leaf.type != LEAF_INT)
	fatal_error_println
	    ("OMF built-in function write() expects INT expr as 1st argument.");

    //if (expr_data->u.leaf.type != LEAF_STRING)
//      fatal_error_println
//          ("OMF built-in function open() expects STRING expr as 2nd argument.");

    INTVAL_P iv = expr_fd->u.leaf.val.int_val;	//TODO: move to util func to check if positive also as in sleep.c
    int fd = iv->ulong_val;
    char *str_data = leaf_val_to_str(expr_data);

    int rr;

    rr = write(fd, str_data, strlen(str_data));
    if (rr < 0)			// NOTE: perhaps verify it is same as str len also
	fatal_error_perror("write()");	// NOTE: should be fatal or perhaps just return -1 so as not to end calling program?? FIXME

    return NULL;
}
